import { createRouter, createWebHashHistory } from "vue-router"
import { useRoute } from '@/contants/router'
import { useLocalStorage } from '@/hooks/useLocalStorage'
import AuthService from '@/service/auth'
import { pinia, useMenusStore } from '@/stores/index'
const menusStore = useMenusStore(pinia)


const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: useRoute
})

// FIXME: 目前钩子还未对刷新时做处理，刷新时应该重新获取menus，重新注册menus
router.beforeEach(async (to, _from, next) => {
  if (to.path == '/login') {
    next()
  } else {
    const { state: token } = useLocalStorage('token')
    if (token.value) {
      if (menusStore.$state.menus && menusStore.$state.menus.length > 0) {
        next()
        return
      }
      await AuthService.getMenus()
      next(to.path)
    } else {
      next('/login')
    }
  }
})

export default router
